if not pattern then pattern = {} end

if not pattern.headoff then

pattern.headoff = {last_time = {}}

if not ScriptsRootPath then
	ScriptsRootPath = getScriptPath() .. "\\..\\"
end

pattern.headoff.patterns_init = lib.path.init .. "patterns.ini"

dofile (ScriptsRootPath .. "lib\\lib.lua")

function pattern.headoff.Init()
	pattern.headoff.params = lib:LoadIni(pattern.headoff.patterns_init, "headoff", {trend = 1, period = 4})
	if processor and processor.log then
		processor:log("pattern.headoff.params", pattern.headoff.params)
	end
end

function pattern.headoff.OnCandle(source, index, data)
	if not source then return end
	if not index then index = 1 end
	if not pattern.headoff.params then pattern.headoff.Init() end
			
	local first_candle = lib:GetLastCandle(source, index + pattern.headoff.params.period)
	local last_candle = lib:GetLastCandle(source, index)
	if first_candle and last_candle then
		local datetime = lib:tickseconds(last_candle.datetime)
		local sec = datetime - lib:tickseconds(first_candle.datetime)
		if sec == pattern.headoff.params.period * 60		-- M1 only
			and (not pattern.headoff.last_time[first_candle.instrument.code]
					or math.abs(pattern.headoff.last_time[first_candle.instrument.code] - datetime)
						> sec
				)
		then
			pattern.headoff.last_time[first_candle.instrument.code] = nil
			--message(first_candle.instrument.code .. " " .. sec .. " " .. (pattern.headoff.params.period * 60))
			local pmin, pmax, is_long = lib:GetCandleRange(source, index, pattern.headoff.params.period)
			if pmin then
				local percent = round((pmax - pmin) * 100 / pmin, 2)
				local price
				
				if percent >= pattern.headoff.params.trend then
					if is_long then
						price = pmin
					else
						price = pmax
					end
										
					pattern.headoff.last_time[first_candle.instrument.code] = datetime
					
					datetime = last_candle.datetime
					datetime.is_long__ = is_long
					
					datetime.hint__ = string.format("HEADOFF %s %s %s%%",
						lib:FormatPrice(price, first_candle.instrument),
						lib:bool2side(is_long),
						tostring(percent)
					)
					datetime.notify__ = first_candle.instrument.code .. " " .. datetime.hint__

					return price, datetime
				else
					if processor and processor.log then
						processor:log(str)
					end
				end
			end
		end
	end
end

end -- of file
